package com.ivr.cm;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.hisunsray.intersp.TCPSpServer;
import com.hisunsray.vspp.data.ClientVO;
import com.hisunsray.vspp.data.PacketHeadVO;
import com.hisunsray.vspp.data.PacketInfoVO;
import com.ivr.cm.data.BaseData;
import com.ivr.cm.handler.BaseHandler;
import com.ivr.cm.handler.HandlerFactory;
import com.ivr.cm.util.SpringServiceUtil;

/**
 * 业务处理线程
 * 对vspp协议进行隔离
 * @author liugeng
 * 2015-12-15
 * @version 1.0
 */
public class HandleThread implements Runnable {
	private static Logger logger = Logger.getLogger(HandleThread.class);
	/**高阳包体VO*/
	private PacketInfoVO packetInfo;
	/**SP TCP服务类*/
	private TCPSpServer tcpServer;
	/**定义操作工厂类 用工具类从Spring配置文件中获得*/
	private HandlerFactory handlerFactory;
	
	public HandleThread(PacketInfoVO packetInfo,TCPSpServer tcpServer){
		this.packetInfo = packetInfo;
		this.tcpServer = tcpServer;
		
		handlerFactory = (HandlerFactory) SpringServiceUtil.getService("handlerFactory");
	}

	@Override
	public void run() {
		BaseHandler handler = null;
		
		if(packetInfo.getPaHeadVO().getCalledNUMBER() != null && packetInfo.getPaHeadVO().getCalledNUMBER().length() >= 9){
			/**正式环境*/
			handler = handlerFactory.getHandler(packetInfo.getPaHeadVO().getCalledNUMBER().substring(0,9), 
					packetInfo.getPaHeadVO().getServerID(), 
					packetInfo.getPaHeadVO().getOperateID());
			
			/**测试环境*/
//			handler = handlerFactory.getHandler(packetInfo.getPaHeadVO().getCalledNUMBER(), 
//					packetInfo.getPaHeadVO().getServerID(), 
//					packetInfo.getPaHeadVO().getOperateID());
		}else{
			logger.error(String.format("[%s]传入参数错误 CalledNumber[%s]", packetInfo.getPaHeadVO().getCallingNUMBER(),packetInfo.getPaHeadVO().getCalledNUMBER()));
			return;
		}
		
		//业务处理
		BaseData data = new BaseData();
		data.setServiceId(packetInfo.getPaHeadVO().getServerID());
		data.setOperateId(packetInfo.getPaHeadVO().getOperateID());
		data.setCalling(packetInfo.getPaHeadVO().getCallingNUMBER());
		data.setLong_called(packetInfo.getPaHeadVO().getCalledNUMBER());
		data.setShort_called(packetInfo.getPaHeadVO().getCalledNUMBER().substring(0,9));
		data.setBody(packetInfo.getPacketBody());
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowDateStr = format.format(new Date());
		String seqNo = packetInfo.getPaHeadVO().getSeqNo();
		if(seqNo != null && !"".equals(seqNo)){
			int seqNoLength = seqNo.length();
			if(seqNoLength > 6){
				seqNo = seqNo.substring(seqNoLength - 6, seqNoLength);
			}else if(seqNoLength < 6){
				String prv_seqNo = "";
				for(int i = 0; i < (6 - seqNoLength); i++){
					prv_seqNo += "0";
				}
				
				seqNo = prv_seqNo + seqNo;
			}
			
			data.setLinkId(nowDateStr + seqNo);
		}
		
		logger.info(String.format("[%s][%s]开始业务处理,处理类:%s", data.getCalling(), data.getLong_called(), handler.getClass().getSimpleName()));
		
		long start_time = System.currentTimeMillis();
		String response = handler.doAction(data);
		long end_time = System.currentTimeMillis();
		logger.info(String.format("[%s][%s]业务处理完成,耗时%dms",data.getCalling(), data.getLong_called(), (end_time-start_time)));
		
		//拼装返回包
		ClientVO clientVO = packetInfo.getClientVO();
		PacketHeadVO packetHead = packetInfo.getPaHeadVO();
		packetHead.setSubCommand("02");  //01代表业务请求  02代表业务请求应答
		packetInfo.setPaHeadVO(packetHead);
		packetInfo.setPacketBody(response);
		
		//发送给高阳
		try{
			tcpServer.vsppSendMessage(clientVO, packetInfo);
			long send_time = System.currentTimeMillis();
			logger.info(String.format("[%s][%s]发送给高阳成功,seqNO=%s,body=%s,发送耗时%dms",data.getCalling(), data.getLong_called(), packetInfo.getPaHeadVO().getSeqNo(), packetInfo.getPacketBody(), (send_time - end_time)));
		}catch (Exception e) {
			logger.error(String.format("[%s][%s]发送给高阳失败,seqNO=%s,失败原因%s",data.getLong_called(),data.getCalling(),packetInfo.getPaHeadVO().getSeqNo(),e.toString()));
			return;
		}
	}
}
